package com.freshfresh.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 正则匹配
 * 
 * @author tang.gw
 * 
 */
public class RegexPattern {

	private static final String URL = "[a-zA-z]+://[^\\s]*";
	private static final String EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
	private static final String CHARS = "[`~!@#$%^&*()+ =|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
	private static final String TEL = "\\d{3}-\\d{8}|\\d{4}-\\d{8}|\\d{4}-\\d{7}|\\d{3}-\\d{7}|\\d{3}\\d{8}|\\d{4}\\d{8}|\\d{3}\\d{7}|\\d{4}\\d{7}";
	private static final String ID_CARD_NO ="^(\\d{15}$|^\\d{18}$|^\\d{17}(\\d|X|x))$";
	private static final String PHONE = "^((13[0-9])|(14[0-9])|(15[0-9])|(18[0,0-9]))\\d{8}$";
	private static final String NUMBER="^[0-9]+(\\.[0-9]+)?$";
	
	public static boolean isNumber(String value){
		if(StringUtil.isBlank(value)){
			return false;
		}
		return value.matches(NUMBER);
	}
	/**
	 * 匹配手机号码
	 * 
	 * @param value
	 * @return
	 */
	public static boolean isPhone(String value) {
		if(StringUtil.isBlank(value)){
			return false;
		}
		return value.matches(PHONE);
	}

	/**
	 * 匹配身份证
	 * 
	 * @param value
	 * @return
	 */
	public static boolean isIdCardNo(String value) {
		if(StringUtil.isBlank(value)){
			return false;
		}
		return value.matches(ID_CARD_NO);
	}
	/**
	 * 匹配国内电话号码
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isTel(String value) {
		if(StringUtil.isBlank(value)){
			return false;
		}
		if (value.trim().equals("")) {
			return true;
		}
		return value.matches(TEL);
	}

	/**
	 * 检测非法字符
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isChars(String str) {
		Pattern p = Pattern.compile(CHARS);
		Matcher m = p.matcher(str);
		return m.find();
	}

	/**
	 * 检测Email
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmail(String email) {
		if(StringUtil.isBlank(email)){
			return false;
		}
		return Pattern.matches(EMAIL, email);
	}

	public static boolean isUrl(String url) {
		if(StringUtil.isBlank(url)){
			return false;
		}
		return Pattern.matches(URL, url);
	}

	public static String encode(String regex) {
		if (regex.indexOf("[") != -1)
			regex = regex.replace("[", "\\[");
		if (regex.indexOf("]") != -1)
			regex = regex.replace("]", "\\]");
		if (regex.indexOf("(") != -1)
			regex = regex.replace("(", "\\(");
		if (regex.indexOf(")") != -1)
			regex = regex.replace(")", "\\)");
		return regex;
	}
}
